using DocumentCreationSystem.Models.AgentOps;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Text.Json;
using System.Threading.Tasks;

using AgentOpsStepType = DocumentCreationSystem.Models.AgentOps.StepType;

namespace DocumentCreationSystem.Services.AgentOps
{
    /// <summary>
    /// 智能规划模板执行器实现 - 解析规划文件并转换为可执行工作流
    /// </summary>
    public class PlanningTemplateExecutor : IPlanningTemplateExecutor
    {
        private readonly ILogger<PlanningTemplateExecutor> _logger;
        private readonly IAIService _aiService;

        public PlanningTemplateExecutor(
            ILogger<PlanningTemplateExecutor> logger,
            IAIService aiService)
        {
            _logger = logger;
            _aiService = aiService;
        }

        /// <summary>
        /// 解析规划模板
        /// </summary>
        public async Task<PlanningTemplate> ParseTemplateAsync(string templatePath)
        {
            try
            {
                _logger.LogInformation($"开始解析规划模板: {templatePath}");

                if (!File.Exists(templatePath))
                {
                    throw new FileNotFoundException($"模板文件不存在: {templatePath}");
                }

                var content = await File.ReadAllTextAsync(templatePath);
                var template = new PlanningTemplate
                {
                    Name = Path.GetFileNameWithoutExtension(templatePath),
                    SourceFilePath = templatePath,
                    Content = new TemplateContent { RawContent = content }
                };

                // 确定模板类型
                template.Type = DetermineTemplateType(templatePath, content);

                // 解析内容结构
                await ParseContentStructureAsync(template, content);

                // 提取任务和变量
                await ExtractTasksAndVariablesAsync(template, content);

                _logger.LogInformation($"模板解析完成: {template.Name}, 类型: {template.Type}");
                return template;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"解析模板失败: {templatePath}");
                throw;
            }
        }

        /// <summary>
        /// 从规划模板创建可执行工作流
        /// </summary>
        public async Task<AgentWorkflow> CreateExecutableWorkflowAsync(
            PlanningTemplate template, 
            WorkflowCreationContext context)
        {
            try
            {
                _logger.LogInformation($"创建可执行工作流: {template.Name}");

                var workflow = new AgentWorkflow
                {
                    Name = $"执行_{template.Name}",
                    Description = $"基于模板 {template.Name} 创建的可执行工作流",
                    Type = ConvertTemplateTypeToWorkflowType(template.Type),
                    SourceTemplateId = template.Id,
                    ProjectId = context.ProjectId,
                    CreatedBy = context.UserId,
                    Priority = context.Options.Priority
                };

                // 根据模板类型创建相应的工作流步骤
                switch (template.Type)
                {
                    case TemplateType.CharacterPlanning:
                        await CreateCharacterPlanningStepsAsync(workflow, template);
                        break;
                    case TemplateType.WorkflowPlanning:
                        await CreateWorkflowPlanningStepsAsync(workflow, template);
                        break;
                    case TemplateType.QualityControl:
                        await CreateQualityControlStepsAsync(workflow, template);
                        break;
                    case TemplateType.Hybrid:
                        await CreateHybridWorkflowStepsAsync(workflow, template);
                        break;
                    default:
                        await CreateGenericWorkflowStepsAsync(workflow, template);
                        break;
                }

                // 设置工作流配置
                workflow.Configuration = new WorkflowConfiguration
                {
                    TimeoutMinutes = context.Options.TimeoutMinutes,
                    AllowParallelExecution = context.Options.EnableMonitoring,
                    AutoRetryOnFailure = true,
                    Notifications = new NotificationConfiguration
                    {
                        Enabled = context.Options.EnableNotifications,
                        Events = { NotificationEvent.WorkflowStarted, NotificationEvent.WorkflowCompleted, NotificationEvent.WorkflowFailed },
                        Channels = { NotificationChannel.UI, NotificationChannel.Log }
                    }
                };

                _logger.LogInformation($"工作流创建完成: {workflow.Name}, 步骤数: {workflow.Steps.Count}");
                return workflow;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"创建可执行工作流失败: {template.Name}");
                throw;
            }
        }

        /// <summary>
        /// 验证模板完整性
        /// </summary>
        public async Task<TemplateValidationResult> ValidateTemplateAsync(PlanningTemplate template)
        {
            var result = new TemplateValidationResult { IsValid = true };

            try
            {
                _logger.LogInformation($"验证模板: {template.Name}");

                // 基本验证
                if (string.IsNullOrEmpty(template.Name))
                {
                    result.Errors.Add("模板名称不能为空");
                    result.IsValid = false;
                }

                if (string.IsNullOrEmpty(template.Content.RawContent))
                {
                    result.Errors.Add("模板内容不能为空");
                    result.IsValid = false;
                }

                // 内容结构验证
                if (template.Content.Sections.Count == 0)
                {
                    result.Warnings.Add("模板中未找到有效的章节结构");
                }

                // 任务验证
                foreach (var task in template.Content.Tasks)
                {
                    if (string.IsNullOrEmpty(task.Name))
                    {
                        result.Errors.Add($"任务 {task.Id} 缺少名称");
                        result.IsValid = false;
                    }

                    if (task.EstimatedMinutes <= 0)
                    {
                        result.Warnings.Add($"任务 {task.Name} 缺少有效的时间估算");
                    }
                }

                // 变量验证
                foreach (var variable in template.Content.Variables.Values)
                {
                    if (variable.IsRequired && variable.DefaultValue == null)
                    {
                        result.Errors.Add($"必需变量 {variable.Name} 缺少默认值");
                        result.IsValid = false;
                    }
                }

                // 使用AI进行深度验证
                if (result.IsValid)
                {
                    await PerformAIValidationAsync(template, result);
                }

                _logger.LogInformation($"模板验证完成: {template.Name}, 有效: {result.IsValid}");
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"验证模板时发生错误: {template.Name}");
                result.IsValid = false;
                result.Errors.Add($"验证过程中发生异常: {ex.Message}");
                return result;
            }
        }

        /// <summary>
        /// 获取模板执行预估
        /// </summary>
        public async Task<TemplateExecutionEstimate> GetExecutionEstimateAsync(PlanningTemplate template)
        {
            try
            {
                _logger.LogInformation($"计算执行预估: {template.Name}");

                var estimate = new TemplateExecutionEstimate
                {
                    TemplateId = template.Id,
                    TemplateName = template.Name
                };

                // 计算总时间估算
                var totalMinutes = template.Content.Tasks.Sum(t => t.EstimatedMinutes);
                estimate.EstimatedDurationMinutes = totalMinutes;

                // 计算资源需求
                estimate.ResourceRequirements = new ResourceRequirements
                {
                    CpuIntensive = template.Content.Tasks.Any(t => t.Type == TaskType.GenerateContent),
                    MemoryIntensive = template.Content.Tasks.Count > 10,
                    DiskSpaceRequired = CalculateDiskSpaceRequirement(template),
                    NetworkRequired = template.Content.Tasks.Any(t => t.Type == TaskType.ProcessData)
                };

                // 计算复杂度评分
                estimate.ComplexityScore = CalculateComplexityScore(template);

                // 计算风险评估
                estimate.RiskFactors = await AnalyzeRiskFactorsAsync(template);

                // 生成执行建议
                estimate.ExecutionRecommendations = GenerateExecutionRecommendations(template, estimate);

                _logger.LogInformation($"执行预估完成: {template.Name}, 预估时间: {totalMinutes}分钟");
                return estimate;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"计算执行预估失败: {template.Name}");
                throw;
            }
        }

        // 私有辅助方法

        private TemplateType DetermineTemplateType(string filePath, string content)
        {
            var fileName = Path.GetFileName(filePath).ToLower();
            
            if (fileName.Contains("角色规划") || fileName.Contains("character"))
                return TemplateType.CharacterPlanning;
            else if (fileName.Contains("工作流规划") || fileName.Contains("workflow"))
                return TemplateType.WorkflowPlanning;
            else if (fileName.Contains("质量控制") || fileName.Contains("quality"))
                return TemplateType.QualityControl;
            else if (content.Contains("角色") && content.Contains("工作流"))
                return TemplateType.Hybrid;
            else
                return TemplateType.ProjectManagement;
        }

        private async Task ParseContentStructureAsync(PlanningTemplate template, string content)
        {
            var lines = content.Split('\n', StringSplitOptions.RemoveEmptyEntries);
            var currentSection = new TemplateSection();
            var sectionStack = new Stack<TemplateSection>();

            foreach (var line in lines)
            {
                var trimmedLine = line.Trim();
                
                if (trimmedLine.StartsWith("#"))
                {
                    // 处理标题
                    var level = trimmedLine.TakeWhile(c => c == '#').Count();
                    var title = trimmedLine.Substring(level).Trim();
                    
                    var section = new TemplateSection
                    {
                        Title = title,
                        Level = level,
                        Type = DetermineSectionType(title)
                    };

                    // 处理层级关系
                    while (sectionStack.Count > 0 && sectionStack.Peek().Level >= level)
                    {
                        sectionStack.Pop();
                    }

                    if (sectionStack.Count > 0)
                    {
                        section.ParentId = sectionStack.Peek().Id;
                        sectionStack.Peek().Children.Add(section);
                    }
                    else
                    {
                        template.Content.Sections.Add(section);
                    }

                    sectionStack.Push(section);
                    currentSection = section;
                }
                else if (!string.IsNullOrEmpty(trimmedLine))
                {
                    // 添加内容到当前章节
                    if (currentSection != null)
                    {
                        currentSection.Content += trimmedLine + "\n";
                    }
                }
            }
        }

        private async Task ExtractTasksAndVariablesAsync(PlanningTemplate template, string content)
        {
            // 提取任务（基于特定模式）
            var taskPattern = @"(?:步骤|任务|Step|Task)\s*(\d+)[：:]\s*(.+?)(?=(?:步骤|任务|Step|Task)\s*\d+|$)";
            var taskMatches = Regex.Matches(content, taskPattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);

            foreach (Match match in taskMatches)
            {
                var order = int.Parse(match.Groups[1].Value);
                var description = match.Groups[2].Value.Trim();

                var task = new TemplateTask
                {
                    Name = $"步骤{order}",
                    Description = description,
                    Order = order,
                    Type = DetermineTaskType(description),
                    EstimatedMinutes = EstimateTaskDuration(description)
                };

                template.Content.Tasks.Add(task);
            }

            // 提取变量（基于占位符模式）
            var variablePattern = @"\{\{(\w+)\}\}";
            var variableMatches = Regex.Matches(content, variablePattern);

            foreach (Match match in variableMatches)
            {
                var variableName = match.Groups[1].Value;
                if (!template.Content.Variables.ContainsKey(variableName))
                {
                    template.Content.Variables[variableName] = new TemplateVariable
                    {
                        Name = variableName,
                        Type = VariableType.String,
                        IsRequired = true,
                        Description = $"模板变量: {variableName}"
                    };
                }
            }
        }

        private SectionType DetermineSectionType(string title)
        {
            var lowerTitle = title.ToLower();
            
            if (lowerTitle.Contains("配置") || lowerTitle.Contains("设置"))
                return SectionType.Configuration;
            else if (lowerTitle.Contains("任务") || lowerTitle.Contains("步骤"))
                return SectionType.Task;
            else if (lowerTitle.Contains("数据") || lowerTitle.Contains("信息"))
                return SectionType.Data;
            else
                return SectionType.Content;
        }

        private TaskType DetermineTaskType(string description)
        {
            var lowerDesc = description.ToLower();
            
            if (lowerDesc.Contains("角色") || lowerDesc.Contains("人物"))
                return TaskType.CreateCharacter;
            else if (lowerDesc.Contains("生成") || lowerDesc.Contains("创建"))
                return TaskType.GenerateContent;
            else if (lowerDesc.Contains("文件") || lowerDesc.Contains("保存"))
                return TaskType.CreateFile;
            else if (lowerDesc.Contains("检查") || lowerDesc.Contains("验证"))
                return TaskType.QualityCheck;
            else
                return TaskType.Custom;
        }

        private int EstimateTaskDuration(string description)
        {
            // 基于描述长度和复杂度估算时间
            double baseTime = Math.Max(5, description.Length / 20); // 基础时间（使用 double 以支持系数放大）
            
            if (description.ToLower().Contains("生成") || description.ToLower().Contains("创建"))
                baseTime *= 2; // 生成任务需要更多时间
            
            if (description.ToLower().Contains("详细") || description.ToLower().Contains("完整"))
                baseTime *= 1.5; // 详细任务需要更多时间
            
            return (int)Math.Min(baseTime, 60); // 最多60分钟
        }

        private WorkflowType ConvertTemplateTypeToWorkflowType(TemplateType templateType)
        {
            return templateType switch
            {
                TemplateType.CharacterPlanning => WorkflowType.CharacterPlanning,
                TemplateType.WorkflowPlanning => WorkflowType.ContentCreation,
                TemplateType.QualityControl => WorkflowType.QualityControl,
                TemplateType.ProjectManagement => WorkflowType.ProjectManagement,
                _ => WorkflowType.Custom
            };
        }

        private async Task CreateCharacterPlanningStepsAsync(AgentWorkflow workflow, PlanningTemplate template)
        {
            // 为角色规划创建特定的工作流步骤
            var steps = new List<WorkflowStep>
            {
                new WorkflowStep
                {
                    Name = "解析角色规划内容",
                    Description = "分析和解析角色规划模板中的角色信息",
                    Type = AgentOpsStepType.DataProcessing,
                    Order = 1,
                    EstimatedDurationMinutes = 5
                },
                new WorkflowStep
                {
                    Name = "生成主要角色",
                    Description = "基于规划内容生成主要角色的详细设定",
                    Type = AgentOpsStepType.AIGeneration,
                    Order = 2,
                    EstimatedDurationMinutes = 15,
                    Dependencies = { workflow.Steps.FirstOrDefault()?.Id ?? "" }
                },
                new WorkflowStep
                {
                    Name = "生成配角设定",
                    Description = "创建配角的基本信息和背景设定",
                    Type = AgentOpsStepType.AIGeneration,
                    Order = 3,
                    EstimatedDurationMinutes = 10
                },
                new WorkflowStep
                {
                    Name = "建立角色关系",
                    Description = "定义角色之间的关系网络和互动模式",
                    Type = AgentOpsStepType.DataProcessing,
                    Order = 4,
                    EstimatedDurationMinutes = 8
                },
                new WorkflowStep
                {
                    Name = "生成角色文档",
                    Description = "将角色信息整理成标准化的文档格式",
                    Type = AgentOpsStepType.FileOperation,
                    Order = 5,
                    EstimatedDurationMinutes = 5
                }
            };

            workflow.Steps.AddRange(steps);
        }

        private async Task CreateWorkflowPlanningStepsAsync(AgentWorkflow workflow, PlanningTemplate template)
        {
            // 为工作流规划创建步骤
            // 实现类似的逻辑...
            await Task.CompletedTask;
        }

        private async Task CreateQualityControlStepsAsync(AgentWorkflow workflow, PlanningTemplate template)
        {
            // 为质量控制创建步骤
            // 实现类似的逻辑...
            await Task.CompletedTask;
        }

        private async Task CreateHybridWorkflowStepsAsync(AgentWorkflow workflow, PlanningTemplate template)
        {
            // 为混合类型创建步骤
            // 实现类似的逻辑...
            await Task.CompletedTask;
        }

        private async Task CreateGenericWorkflowStepsAsync(AgentWorkflow workflow, PlanningTemplate template)
        {
            // 为通用类型创建步骤
            // 实现类似的逻辑...
            await Task.CompletedTask;
        }

        private async Task PerformAIValidationAsync(PlanningTemplate template, TemplateValidationResult result)
        {
            // 使用AI进行深度验证
            // 实现AI验证逻辑...
            await Task.CompletedTask;
        }

        private long CalculateDiskSpaceRequirement(PlanningTemplate template)
        {
            // 计算磁盘空间需求
            return template.Content.Tasks.Count * 1024 * 1024; // 每个任务预估1MB
        }

        private double CalculateComplexityScore(PlanningTemplate template)
        {
            // 计算复杂度评分
            var score = 0.0;
            score += template.Content.Sections.Count * 0.1;
            score += template.Content.Tasks.Count * 0.2;
            score += template.Content.Variables.Count * 0.1;
            return Math.Min(score, 1.0);
        }

        private async Task<List<string>> AnalyzeRiskFactorsAsync(PlanningTemplate template)
        {
            var risks = new List<string>();
            
            if (template.Content.Tasks.Count > 20)
                risks.Add("任务数量过多，可能导致执行时间过长");
            
            if (template.Content.Tasks.Any(t => t.EstimatedMinutes > 30))
                risks.Add("存在耗时较长的任务，可能影响整体进度");
            
            return risks;
        }

        private List<string> GenerateExecutionRecommendations(PlanningTemplate template, TemplateExecutionEstimate estimate)
        {
            var recommendations = new List<string>();
            
            if (estimate.EstimatedDurationMinutes > 60)
                recommendations.Add("建议启用并行执行以缩短总执行时间");
            
            if (estimate.ComplexityScore > 0.7)
                recommendations.Add("模板复杂度较高，建议分阶段执行");
            
            return recommendations;
        }

        public Task<PlanningTemplate> OptimizeTemplateAsync(PlanningTemplate template, TemplateOptimizationOptions optimizationOptions)
        {
            throw new NotImplementedException();
        }

        public Task<TemplateDiffResult> CompareTemplatesAsync(PlanningTemplate template1, PlanningTemplate template2)
        {
            throw new NotImplementedException();
        }

        public Task<TemplateExecutionReport> GenerateExecutionReportAsync(string templateId, List<WorkflowExecutionResult> executionResults)
        {
            throw new NotImplementedException();
        }
    }
}
